#ifndef __TCPCONNECT_HPP__
#define __TCPCONNECT_HPP__

#include "SocketIO.hpp"
#include "Socket.hpp"
#include "InetAddress.hpp"
#include <functional>
#include <memory>
using std::function;
using std::shared_ptr;

namespace wd{

class EventLoop;
//保存建立连接的客户fd
class TcpConnection:public std::enable_shared_from_this<TcpConnection>{
    using TcpConnectionptr = shared_ptr<TcpConnection>;
    using Callback = function<void(TcpConnectionptr)>;
    friend class EventLoop;
public:
    TcpConnection(int clientfd, EventLoop*);
    string receive();
    void send(const string&);
    bool isclose() const;
    void sendInLoop(const string & msg);

private:
    void setAllCallbacks(const Callback & onConnection,
                         const Callback & onMessage,
                         const Callback & onClose);

    void handleNewConnectionCallback(){
        _onConnection(shared_from_this());
    }
    void handleMessageCallback(){
        _onMessage(shared_from_this());
    }
    void handleCloseCallback(){
        _onClose(shared_from_this());
    }

private:
    struct sockaddr_in getLocalAddr();
    struct sockaddr_in getPeerAddr();


private:
    Socket _sock;
    SocketIO _sockio;
    InetAddress _localAddr;
    InetAddress _peerAddr;
    EventLoop * _peventloop;

    Callback _onConnection;
    Callback _onMessage;
    Callback _onClose;
};

}

#endif // __TCPCONNECT_HPP__

